package com.jamie.seata.order.service;

import com.jamie.seata.AccountService;
import com.jamie.seata.Order;
import com.jamie.seata.OrderService;
import com.jamie.seata.StorageService;
import com.jamie.seata.order.dao.OrderDao;
import io.seata.core.context.RootContext;
import io.seata.spring.annotation.GlobalTransactional;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

/**
 * @author 594781919@qq.com
 * @date 2019-10-11
 **/
@Service
public class OrderServiceImpl implements OrderService {

    @Reference
    private AccountService accountService;

    @Reference
    private StorageService storageService;

    @Resource
    private OrderDao orderDao;

    @Override
    @Transactional(rollbackFor = Exception.class)
    @GlobalTransactional
    public Order create(String userId, String commodityCode, int orderCount) {
        final int money = 5000;
        Order order = new Order();
        order.setUserId(userId);
        order.setCommodityCode(commodityCode);
        order.setCount(orderCount);
        order.setMoney(money);

        orderDao.save(order);

        System.out.println("当前xid: " + RootContext.getXID());

        storageService.deduct(commodityCode, orderCount);

        accountService.debit(userId, money);

        if (orderCount < 1) {
            throw new RuntimeException("订单数量不能小于1，orderCount=" + orderCount);
        }

        return order;
    }
}
